import { FC, useState, ChangeEvent, useEffect } from 'react';

import Child from './components/Child';

// CSS Modules, 样式不会相互干扰
import style from './index.less';

import logo from '../../assets/result.png';

import { Button } from 'antd';

interface ListItemType {
  id: number;
  name: string;
}

const Index: FC = () => {
  // <number>泛型的写法定义useState的变量的类型
  const [count, setCount] = useState<number>(5);
  const [value, setValue] = useState<string>('');
  const [list, setList] = useState<ListItemType[]>([]);

  useEffect(() => {
    // fetch('http://localhost:8000/api/users')
    //   .then((response) => response.json())
    //   .then((res) => {
    //     setList(res.result);
    //   });
    fetch(
      '/api/mmdb/movie/v3/list/hot.json?ct=%E6%9D%AD%E5%B7%9E&ci=50&channelId=4',
    )
      .then((response) => response.json())
      .then((res) => {
        console.log(res);
      });
  }, []);

  // 函数只需要写函数返回值类型
  const add = (): void => {
    setCount((v) => v + 1);
  };

  const onChange = (e: ChangeEvent<HTMLInputElement>): void => {
    setValue(e.target.value);
  };

  const add2 = (): void => {
    setList((v: ListItemType[]) => {
      return [
        ...v,
        {
          id: new Date().getTime(),
          name: value,
        },
      ];
    });
  };

  const remove = (id: number): void => {
    setList((v) => v.filter((item) => item.id !== id));
  };

  return (
    <>
      <h1>这是ts页面</h1>
      <span className={style.count}>{count}</span>
      <button onClick={add}>+</button>

      <hr />

      <input type="text" value={value} onChange={onChange} />
      <button onClick={add2}>添加</button>
      <ul>
        {list.map((item: ListItemType) => {
          return (
            <li key={item.id}>
              {item.name} -{' '}
              <button onClick={() => remove(item.id)}>删除</button>
            </li>
          );
        })}
      </ul>

      <hr />

      <Child count={count} a="3" b={10} />

      <hr />

      {/* <img src={require('../../assets/result.png')} alt="" /> */}
      <img src={logo} alt="" />

      <hr />

      <Button type="primary">Primary Button</Button>
    </>
  );
};

export default Index;
